package org.example.pet.interceptor;

import org.example.pet.common.expection.AuthenticationException;
import org.example.pet.service.UserService;
import org.example.pet.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行OPTIONS预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        
        // 获取Token（格式：Bearer xxx）
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            throw new AuthenticationException("未登录，请先登录");
        }
        // 拿出真正的token
        token = token.substring(7);

        try {
            // 解析Token并验证
            String username = jwtUtil.getUsernameFromToken(token);
            if (userService.getUserByUsername(username) == null) {
                throw new AuthenticationException("用户不存在");
            }
            if (!jwtUtil.validateToken(token, username)) {
                throw new AuthenticationException("登录已过期，请重新登录");
            }

            // 存储角色到request域
            String role = jwtUtil.getRoleFromToken(token);
            request.setAttribute("currentRole", role);
            return true;
        } catch (AuthenticationException e) {
            throw e;
        } catch (Exception e) {
            throw new AuthenticationException("Token无效，请重新登录");
        }
    }
}